package com.fh.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fh.annotation.IgnoreAuth;
import com.fh.util.R;

/**
 * token_认证拦截
 * 
 * @author cdf
 *
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) {
		IgnoreAuth annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler)
					.getMethodAnnotation(IgnoreAuth.class);
		} else {
			return true;
		}

		if (annotation != null) {
			return true;
		}

		String _token = request.getHeader("access_token");
		if (StringUtils.isBlank(_token)) {
			_token = request.getParameter("access_token");
		}
		if (StringUtils.isBlank(_token)) {
			JSONObject j = JSONObject.fromObject(R.error("token is not null"));
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			try {
				response.getWriter().print(j.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}
}
